package net.ib.mtalk.util;


public class NameSearch {
	
	private static final char KOREAN_BEGIN_UNICODE = 44032; //가  
	private static final char KOREAN_LAST_UNICODE = 55203; //    
	private static final char KOREAN_BASE_UNIT = 588; //각자음마다 가지는 글자수
	private static final char[] INITIAL_SOUND = { 'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' };  
	
	public static boolean isMatch(String list, String search){
		int t = 0;
		int seof = list.length() - search.length();
		int slen = search.length();
		String ignoreCaseList = list.toUpperCase();
		String ignoreCaseSearch = search.toUpperCase();
		
		if(seof < 0){
			return false;
		}
		
		for(int i = 0 ; i <= seof ; i++){
			
			while ( t < slen){
				if(isInitial(search.charAt(t)) && isKorean(list.charAt(i+t))){
					if(getInitial(list.charAt(i+t))== search.charAt(t))
						t++;
					else break;
				}else{
					if(ignoreCaseList.charAt(i+t) == ignoreCaseSearch.charAt(t))
						t++;
					else break;
				}
				
			}
			if(t == slen) return true;
		}
		return false;
	}
	
	private static char getInitial(char c){
		int first = (c - KOREAN_BEGIN_UNICODE);
		int index = first / KOREAN_BASE_UNIT;
		return INITIAL_SOUND[index];
	}
	
	private static boolean isKorean(char c){
		return (KOREAN_BEGIN_UNICODE <= c && c <= KOREAN_LAST_UNICODE);
	}
	
	private static boolean isInitial(char forSearch){
		for(char c : INITIAL_SOUND){
			if(c == forSearch){
				return true;
			}
		}
		
		return false;
	}
}
